import {
	Button,
	Collapse,
	Form,
	Row,
	Col,
	Input,
	Switch,
	Checkbox,
	TreeSelect,
	Transfer,
	Tree,
	Table,
	Space,
	Modal,
	message,
} from 'antd'
import React, {useState, useEffect} from 'react'
import {history, connect} from 'umi'
import styles from '@/assets/common/css/page.less'
import indexLess from './index.less'
import {translateDataToTree} from '@/utils/common/index'
import {getDeptList} from '@/service/system/dept'
import {viewUser, userShareRole} from '@/service/system/user'
import {getMenuList} from '@/service/system/menu'
import {getUserByRoleList, getRoleList} from '@/service/system/role'

import {getCityList} from '@/service/system/company'

const {Panel} = Collapse
const {Search} = Input
const fieldNames = {
	label: 'name',
	value: 'id',
	id: 'id',
	pId: 'parentId',
}

const customizeHeader = (value: string) => (
	<div>
		<div className={styles.tip} />
		{value}
	</div>
)

const addDom = (props: any) => {
	const currentMerchantId = props?.user?.currentMerchantId
	const [userId, setUserId] = useState()
	const [treeData, setTreeData] = useState()
	const [form] = Form.useForm()
	const [menuSource, setMenuSource] = useState<any[]>([])
	// const [selectId, setSelectedId] = useState<any>()
	const [selectedTreeKeys, setSelectedTreeKeys] = useState<any>()

	const [orginRoleSource, setOrginRoleSource] = useState<any>([])
	const [roleSource, setRoleSource] = useState<any>([])
	const [roleLoading, setRoleLoading] = useState(false)
	const [roleName, setRoleNameSource] = useState('')
	const [rowClassName, setRowClassNameSource] = useState<string | number>()
	const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([])
	const [selectedRow, setSelectedRow] = useState<any>([])

	const [isModalOpen, setIsModalOpen] = useState(false)
	const [cityData, setCityData] = useState<any[]>([])
	const [targetKeys, setTargetKeys] = useState<string[]>([])
	const [selectedKeys, setSelectedKeys] = useState<string[]>([])
	const [idKeys, setIdKeys] = useState()

	// 初始化获取用户信息
	const viewUserFun = (uid: any) => {
		viewUser(uid, {merchantId: currentMerchantId}).then((res: any) => {
			if (res?.success) {
				const {status, admin} = res.data
				form.setFieldsValue({
					...res.data,
					status: !!status,
					admin: admin === 1 ? ['check'] : [],
				})
			}
		})
	}

	useEffect(() => {
		const {id} = props.location.query
		setUserId(() => id)
		viewUserFun(id)
	}, [userId])

	// 初始化-菜单数据
	const onListFun = () => {
		getMenuList().then((res: any) => {
			if (res?.success) {
				const list = translateDataToTree(res.data)
				setMenuSource(list as any)
			}
		})
	}

	// 初始化-部门列表
	const getDeptFun = () => {
		getDeptList({merchantId: currentMerchantId}).then((res: any) => {
			if (res?.success) {
				const list = translateDataToTree(res.data)
				setTreeData(list as any)
			}
		})
	}

	// 获取所有城市数据
	const onAllCityFun = () => {
		getCityList({merchantId: currentMerchantId}).then((res: any) => {
			if (res?.success) {
				setCityData([...res.data])
			}
		})
	}

	useEffect(() => {
		onListFun()
		onAllCityFun()
	}, [])
	useEffect(() => {
		if (currentMerchantId) {
			getDeptFun()
		}
	}, [currentMerchantId])

	const onCityFun = (row: any) => {
		setIsModalOpen(true)
		const list = row?.cityList?.map((item: {cityId: any}) => item.cityId)
		setTargetKeys(() => (list ? [...list] : []))
		setIdKeys(() => row.id)
	}

	// 角色及城市维护列表
	const roleColumns = [
		{
			title: '角色名',
			key: 'name',
			ellipsis: true,
			dataIndex: 'name',
		},
		{
			title: '城市',
			key: 'cityList',
			width: 200,
			ellipsis: true,
			dataIndex: 'cityList',
			render: (text: any, record: any) => (
				<>
					{text
						? text?.map((item: any, index: number) => (
								<span>
									{item.cityName}
									{record.cityList.length - 1 === index
										? ''
										: ','}
								</span>
						  ))
						: '--'}
					({record?.cityList?.length}个城市)
				</>
			),
		},
		{
			title: '操作',
			width: 200,
			key: 'opt',
			dataIndex: 'opt',
			render: (
				text: any,
				record: {
					permissionList(id: string, permissionList: any): void
					id: string
				},
			) => (
				<Space size={12}>
					<Button
						className="text_btn"
						type="link"
						size="small"
						onClick={() => onCityFun(record)}>
						维护城市
					</Button>
				</Space>
			),
		},
	]

	// 处理全量角色列表和选中角色及城市数据统一处理
	const getRoleColumns = (allRole: any, roleByUserId: any, key: string) => {
		const combined = allRole.map((item1: any) => {
			const newItem1 = item1
			roleByUserId.map((item2: any) => {
				let newItem2 = item2
				if (newItem1[key] === newItem2[key]) {
					newItem2 = Object.assign(item1, newItem2)
				}
				return newItem2
			})
			return newItem1
		})
		return combined
	}
	// 获取菜单选中
	const menuSelectFun = (list: any) => {
		const permissionList = list
			?.map((item: {permissionList: any}) =>
				item?.permissionList?.map((i: any) => i.id),
			)
			?.flat(Infinity)
		setSelectedTreeKeys(() => Array.from(new Set(permissionList)))
	}

	useEffect(() => {
		menuSelectFun(selectedRow)
	}, [selectedRow])
	// 处理全量角色列表和选中角色及城市
	const getList = () => {
		const {id} = props.location.query
		new Promise((resolve, reject) => {
			setRoleLoading(true)
			getRoleList({merchantId: currentMerchantId, roleName}).then(
				(res: any) => {
					if (res?.success) {
						setRowClassNameSource(res?.data[0]?.id)
						resolve(res?.data)
					} else {
						reject()
					}
				},
			)
		}).then((val: any) => {
			getUserByRoleList(id, {merchantId: currentMerchantId}).then(
				(res: any) => {
					if (res?.success) {
						const ids = res?.data?.map(
							(item: {id: number}) => item.id,
						)
						setSelectedRowKeys(() => ids)
						const list: any = getRoleColumns(val, res?.data, 'id')
						setRoleSource(() => list)
						setOrginRoleSource(() => list)
						setRoleLoading(false)
						setSelectedRow(() => res?.data)
					}
				},
			)
		})
	}

	// 角色搜索
	const onRoleSearch = (value: string) => {
		setRoleNameSource(() => value)
		if (value.trim() === '') {
			setRoleSource(() => orginRoleSource)
		} else {
			const arr = []
			for (let i = 0; i < roleSource.length; i += 1) {
				if (roleSource[i]?.name?.indexOf(value) >= 0) {
					arr?.push(roleSource[i])
				}
			}
			setRoleSource(arr)
		}
	}

	useEffect(() => {
		getList()
	}, [])

	// 用户勾选保存
	const onSelectChange = (
		newSelectedRowKeys: React.Key[],
		newSelectedRow: any,
	) => {
		setSelectedRowKeys(() => newSelectedRowKeys)
		setSelectedRow(() => newSelectedRow)
	}

	// 选中角色
	const onSelectRow = (row: {permissionList: any; id: any}) => {
		// const ids = row.permissionList?.map((item: any) => item.id)
		// setSelectedId(() => ids)
		setRowClassNameSource(() => row?.id)
	}

	// 设置行名称
	const setRowClassName = (record: {id: any}) =>
		record.id === rowClassName ? `clickRowStyl` : ''

	const rowSelection = {
		selectedRowKeys,
		onChange: onSelectChange,
	}

	// 维护城市表单提交
	const submitCity = () => {
		const option = cityData?.filter((item: any) =>
			targetKeys?.includes(item.cityId),
		)
		const list = roleSource?.map((item: any) => {
			let newItem = item
			if (newItem.id === idKeys) {
				newItem = {...newItem, cityList: [...option]}
			}
			return newItem
		})

		const orginList = orginRoleSource?.map((item: any) => {
			let newItem = item
			if (newItem.id === idKeys) {
				newItem = {...newItem, cityList: [...option]}
			}
			return newItem
		})

		setOrginRoleSource(() => orginList)
		setRoleSource(() => list)
		setTargetKeys(() => [])
		setIsModalOpen(false)
	}

	// 表单提交
	const submit = () => {
		const roleList = orginRoleSource
			?.filter((item: any) => selectedRowKeys.includes(item.id))
			.map((item: any) => ({
				cityIdList: item?.cityList
					? item?.cityList.map((i: {cityId: number}) => i.cityId)
					: [],
				roleId: item.id,
			}))
		if (!roleList.length) {
			message.warning('请给用户选择角色')
		} else {
			userShareRole(userId, currentMerchantId, {
				roleList,
			})
				.then((res) => {
					if (res?.success) {
						message.success(res.msg)
						history.goBack()
					}
				})
				.catch((err) => {
					message.error(err)
				})
		}
	}
	// 维护城市表单取消
	const onCancelCity = () => {
		setIsModalOpen(false)
	}

	// 穿梭框选中事件
	const onChange = (nextTargetKeys: any) => {
		setTargetKeys(nextTargetKeys)
	}

	// 穿梭框变化事件
	const onSelectCityChange = (
		sourceSelectedKeys: string[],
		targetSelectedKeys: string[],
	) => {
		setSelectedKeys([...sourceSelectedKeys, ...targetSelectedKeys])
	}

	return (
		<div className={styles.page}>
			<div className={`${styles.content}`}>
				<Row gutter={12}>
					<Col sm={{span: 24}}>
						<Collapse
							defaultActiveKey={['1']}
							ghost
							expandIconPosition="end">
							<Panel header={customizeHeader('基础信息')} key="1">
								<Form
									form={form}
									name="basic"
									layout="horizontal"
									labelCol={{flex: '100px'}}
									labelAlign="right"
									labelWrap
									initialValues={{remember: true}}
									autoComplete="off">
									<Row gutter={12}>
										<Col
											sm={{span: 24}}
											md={{span: 8}}
											lg={{span: 6}}>
											<Form.Item
												label="编号"
												name="id"
												rules={[{required: true}]}>
												<Input
													placeholder="请输入"
													disabled
												/>
											</Form.Item>
										</Col>
										<Col
											md={{span: 8}}
											sm={{span: 24}}
											lg={{span: 6}}>
											<Form.Item
												label="名称"
												name="name"
												rules={[
													{
														required: true,
														message: '请输入名称',
													},
												]}>
												<Input
													placeholder="请输入"
													disabled
												/>
											</Form.Item>
										</Col>
										<Col
											sm={{span: 24}}
											md={{span: 8}}
											lg={{span: 6}}>
											<Form.Item
												label="部门"
												name="departmentId"
												rules={[
													{
														required: true,
														message: '请选择部门',
													},
												]}>
												<TreeSelect
													disabled
													showSearch
													treeNodeFilterProp="name"
													style={{width: '100%'}}
													dropdownStyle={{
														maxHeight: 400,
														overflow: 'auto',
													}}
													placeholder="请选择部门"
													allowClear
													fieldNames={fieldNames}
													treeDefaultExpandAll
													treeData={treeData}
												/>
											</Form.Item>
										</Col>
										<Col
											sm={{span: 24}}
											md={{span: 8}}
											lg={{span: 6}}>
											<Form.Item
												label="手机"
												name="phone"
												rules={[
													{
														required: true,
														message: '请输入手机号',
													},
												]}>
												<Input
													placeholder="请输入手机号"
													disabled
												/>
											</Form.Item>
										</Col>
										<Col
											sm={{span: 24}}
											md={{span: 8}}
											lg={{span: 6}}>
											<Form.Item
												label="邮箱"
												name="mail"
												rules={[
													{
														type: 'email',
														message:
															'填写的邮箱格式有误',
													},
												]}>
												<Input
													placeholder="请输入邮箱"
													disabled
												/>
											</Form.Item>
										</Col>
										<Col
											sm={{span: 24}}
											md={{span: 8}}
											lg={{span: 6}}>
											<Form.Item
												label="状态"
												name="status"
												valuePropName="checked"
												rules={[
													{
														required: true,
														message: '请选择状态',
													},
												]}>
												<Switch disabled />
											</Form.Item>
										</Col>
										<Col
											sm={{span: 24}}
											md={{span: 8}}
											lg={{span: 6}}>
											<Form.Item
												label="是否管理员"
												name="admin">
												<Checkbox.Group>
													<Checkbox
														value="check"
														disabled
													/>
												</Checkbox.Group>
											</Form.Item>
										</Col>
									</Row>
								</Form>
							</Panel>
						</Collapse>
					</Col>
					<Col sm={{span: 24}} md={{span: 12}} lg={{span: 12}}>
						<Collapse
							defaultActiveKey={['1']}
							ghost
							expandIconPosition="end">
							<Panel
								header={customizeHeader('角色及城市维护')}
								key="1">
								<Search
									placeholder="请输入角色名"
									allowClear
									className={indexLess.userSearch}
									enterButton="搜索"
									onSearch={onRoleSearch}
								/>
								<Table
									rowKey={(record) => record.id}
									scroll={{y: 340}}
									columns={roleColumns}
									dataSource={roleSource}
									rowSelection={rowSelection}
									bordered
									loading={roleLoading}
									pagination={false}
									onRow={(record) => ({
										onClick: () => onSelectRow(record),
									})}
									rowClassName={setRowClassName}
								/>
							</Panel>
						</Collapse>
					</Col>
					<Col sm={{span: 24}} md={{span: 12}} lg={{span: 12}}>
						<Collapse
							defaultActiveKey={['1']}
							ghost
							expandIconPosition="end">
							<Panel header={customizeHeader('功能授权')} key="1">
								{menuSource && menuSource.length > 0 ? (
									<Tree
										checkable
										disabled
										checkStrictly
										height={430}
										checkedKeys={selectedTreeKeys}
										treeData={menuSource}
										fieldNames={{
											title: 'name',
											key: 'id',
										}}
										defaultExpandAll
									/>
								) : null}
							</Panel>
						</Collapse>
					</Col>
				</Row>
				<div className={styles.wrap}>
					<Button
						type="primary"
						className="reset"
						htmlType="submit"
						onClick={submit}>
						保存
					</Button>
					<Button
						htmlType="reset"
						onClick={(e) => {
							e.stopPropagation()
							history.goBack()
						}}>
						取消
					</Button>
				</div>
				<Modal
					title="城市维护"
					open={isModalOpen}
					onOk={submitCity}
					onCancel={onCancelCity}
					width={800}
					destroyOnClose
					footer={
						<>
							<Button onClick={onCancelCity}>取消</Button>
							<Button
								type="primary"
								size="small"
								onClick={submitCity}>
								确定
							</Button>
						</>
					}>
					<Row gutter={12}>
						<Col sm={{span: 24}}>
							<Transfer
								dataSource={cityData}
								titles={['未选中的城市', '已选中的城市']}
								targetKeys={targetKeys}
								selectedKeys={selectedKeys}
								render={(item) => item.cityName!}
								rowKey={(record) => record.cityId}
								onChange={onChange}
								onSelectChange={onSelectCityChange}
							/>
						</Col>
					</Row>
				</Modal>
			</div>
		</div>
	)
}
export default connect(({user}: any) => ({
	user,
}))(addDom)
